package com.example.snake;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

public class GameView extends View {
    private static final String TAG = "GameView";
    private Snake snake;
//    private Food food;
    // 在 GameView 类中添加食物列表
    private List<Food> foods = new ArrayList<>();
    private Paint snakePaint;
    private Paint foodPaint;
    private Paint backgroundPaint;
    private int cellSize = 40;
    private int gridSize = 25;
    private Handler handler;
    private Runnable gameLoop;
    private boolean isRunning = false;
    private OnGameEventListener listener;

    public interface OnGameEventListener {
        void onScoreChanged(int score);
        void onGameOver();
    }

    public GameView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        // 初始化蛇对象和食物
        snake = new Snake(5, 5);
//        spawnFood();
        spawnFoods();
        // 设置蛇的绘制画笔
        snakePaint = new Paint();
        snakePaint.setColor(Color.GREEN);
        snakePaint.setStyle(Paint.Style.FILL);
        // 设置食物的绘制画笔
        foodPaint = new Paint();
        foodPaint.setColor(Color.RED);
        foodPaint.setStyle(Paint.Style.FILL);
        // 设置背景的绘制画笔
        backgroundPaint = new Paint();
        backgroundPaint.setColor(Color.BLACK);
        backgroundPaint.setStyle(Paint.Style.FILL);
        // 初始化游戏循环处理器和运行任务
        handler = new Handler();
        gameLoop = new Runnable() {
            @Override
            public void run() {
                update();
                invalidate();
                if (isRunning) {
                    handler.postDelayed(this, 300);
                }
            }
        };
    }

    public void startGame() {
        isRunning = true;
        handler.post(gameLoop);
    }

    public void stopGame() {
        isRunning = false;
        handler.removeCallbacks(gameLoop);
    }

    private void update() {
        snake.move();

        Snake.Point head = snake.getHead();

        // 检查碰撞边界
        if (head.x < 0 || head.x >= gridSize || head.y < 0 || head.y >= gridSize) {
            gameOver();
            return;
        }

        // 检查碰撞自身
        for (int i = 1; i < snake.getBody().size(); i++) {
            Snake.Point bodyPart = snake.getBody().get(i);
            if (head.equals(bodyPart)) {
                gameOver();
                return;
            }
        }

        // 检查吃食物
//        if (head.x == food.x && head.y == food.y) {
//            snake.grow();
//            spawnFood();
//            if (listener != null) {
//                listener.onScoreChanged(snake.getBody().size() - 1);
//            }
//        }
        // 检查吃食物
        Iterator<Food> iterator = foods.iterator();
        while (iterator.hasNext()) {
            Food food = iterator.next();
            if (head.x == food.x && head.y == food.y) {
                snake.grow();
                iterator.remove(); // 移除被吃掉的食物
                if (listener != null) {
                    listener.onScoreChanged(snake.getBody().size() - 1);
                }
            }
        }
        // 如果所有食物都被吃完了，生成新的一批食物
        if (foods.isEmpty()) {
            spawnFoods();
        }
    }
    int[] speedDelays = { 300, 150, 100}; // 对应不同速度级别的时间间隔

    // 在 GameView 类中添加速度控制方法
    public void setSpeedLevel(int level) {
        int delay = speedDelays[Math.min(level - 1, speedDelays.length - 1)];
        // 重新启动游戏循环以应用新速度
        if (isRunning) {
            handler.removeCallbacks(gameLoop);
            gameLoop = new Runnable() {
                @Override
                public void run() {
                    update();
                    invalidate();
                    if (isRunning) {
                        handler.postDelayed(this, delay);
                    }
                }
            };
            handler.post(gameLoop);
        }
    }

    // 循环随机生成坐标，直到找到一个不在蛇身上的位置
//    private void spawnFood() {
//        Random random = new Random();
//        int x, y;
//        do {
//            x = random.nextInt(gridSize);
//            y = random.nextInt(gridSize);
//        } while (isSnakePosition(x, y));
//
//        food = new Food(x, y);
//    }
    private void spawnFoods() {
        Log.d(TAG, "update: 食物");
        Random random = new Random();
        int foodCount = random.nextInt(5) + 1;

        int maxAttempts = gridSize * gridSize;
        int attempts = 0;

        // 补充食物直到达到合理数量
        while (foods.size() < foodCount && attempts < maxAttempts) {
            int x = random.nextInt(gridSize);
            int y = random.nextInt(gridSize);

            // 确保食物位置在有效范围内
            if (x >= 0 && x < gridSize && y >= 0 && y < gridSize) {
                if (!isSnakePosition(x, y) && !isFoodPosition(x, y)) {
                    foods.add(new Food(x, y));
                }
            }
            attempts++;
        }

        Log.d(TAG, "update completed: 食物数量 "+ foods.size());
    }
    // 添加检查食物位置的方法
    private boolean isFoodPosition(int x, int y) {
        for (Food food : foods) {
            if (food.x == x && food.y == y) {
                return true;
            }
        }
        return false;
    }

    private boolean isSnakePosition(int x, int y) {
        for (Snake.Point point : snake.getBody()) {
            if (point.x == x && point.y == y) {
                return true;
            }
        }
        return false;
    }

    private void gameOver() {
        stopGame();
        if (listener != null) {
            listener.onGameOver();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 绘制背景
        canvas.drawRect(0, 0, getWidth(), getHeight(), backgroundPaint);
        // 限制绘制区域不超过屏幕
        int maxWidth = Math.min(getWidth(), gridSize * cellSize);
        int maxHeight = Math.min(getHeight(), gridSize * cellSize);

        // 计算居中绘制的偏移量
        int boardWidth = gridSize * cellSize;
        int boardHeight = gridSize * cellSize;
        int offsetX = (getWidth() - boardWidth) / 2;
        int offsetY = 0;

        // 绘制网格线（居中）
        Paint gridPaint = new Paint();
        gridPaint.setColor(Color.GRAY);
        gridPaint.setStyle(Paint.Style.STROKE);

        // 绘制加粗红色边界画笔
        Paint borderLinePaint = new Paint();
        borderLinePaint.setColor(Color.RED);
        borderLinePaint.setStyle(Paint.Style.STROKE);
        borderLinePaint.setStrokeWidth(3);

        for (int i = 0; i <= gridSize; i++) {
            // 检查是否为边界线
            if (i == 0 || i == gridSize) {
                // 绘制边界横线和竖线（加粗红色）
                canvas.drawLine(offsetX + i * cellSize, offsetY, offsetX + i * cellSize, offsetY + boardHeight, borderLinePaint); // 竖线
                canvas.drawLine(offsetX, offsetY + i * cellSize, offsetX + boardWidth, offsetY + i * cellSize, borderLinePaint); // 横线
            } else {
                // 绘制普通网格线
                canvas.drawLine(offsetX + i * cellSize, offsetY, offsetX + i * cellSize, offsetY + boardHeight, gridPaint);
                canvas.drawLine(offsetX, offsetY + i * cellSize, offsetX + boardWidth, offsetY + i * cellSize, gridPaint);
            }
        }

        // 绘制蛇身（水平居中）
        for (Snake.Point point : snake.getBody()) {
            canvas.drawRect(
                    offsetX + point.x * cellSize,
                    offsetY + point.y * cellSize,
                    offsetX + point.x * cellSize + cellSize,
                    offsetY + point.y * cellSize + cellSize,
                    snakePaint
            );
        }

        // 绘制所有食物（水平居中）
        for (Food food : foods) {
            canvas.drawRect(
                    offsetX + food.x * cellSize,
                    offsetY + food.y * cellSize,
                    offsetX + food.x * cellSize + cellSize,
                    offsetY + food.y * cellSize + cellSize,
                    foodPaint
            );
        }
    }

    public Snake getSnake() {
        return snake;
    }

    public void setOnGameEventListener(OnGameEventListener listener) {
        this.listener = listener;
    }
}
